package org.example.aidemo.controller;

import jakarta.validation.Valid;
import kotlin.Pair;
import org.example.aidemo.pojo.Result;
import org.example.aidemo.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/login")
    public Result<?> login(@Valid @RequestBody Map<String, Object> loginParams) {
        // 1. 进行身份认证
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        (String) loginParams.get("username"),
                        (String) loginParams.get("password"))
        );
        // 2. 认证成功，将Authentication对象存入上下文（可选，JWT过滤器后续会自己处理）
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 3. 获取用户详情，生成JWT
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        List<String> roles = userDetails.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        String jwt = jwtUtils.generateToken(userDetails.getUsername(), roles);
        // 4. 将JWT存入Redis，设置过期时间与JWT一致
        try {
            long expirationTime = 1000 * 60 * 60 * 24; // 24小时（毫秒）
            redisTemplate.opsForValue().set("jwt:" + userDetails.getUsername(),
                    jwt, expirationTime, TimeUnit.MILLISECONDS);
            System.out.println("JWT已存储到Redis: " + "jwt:" + userDetails.getUsername()); // 添加日志确认
        } catch (Exception e) {
            System.err.println("存储JWT到Redis失败: " + e.getMessage());
        }
        // 4. 返回JWT
        Result<Map<String, Object>> result = new Result<>();
        result.setData(new HashMap<>());
        result.getData().put("token", jwt);
        result.getData().put("username", userDetails.getUsername());
        result.setCode("200");
        result.setMsg("登录成功！");
        return result;
    }

    @GetMapping("/me")
    public String getCurrentUserInfo(Authentication authentication) {
        if (authentication != null && authentication.isAuthenticated()) {
            return "登录中！当前用户: " + authentication.getName();
        }
        return "未认证";
    }
    @GetMapping("/logout")
    public String logout(Authentication authentication) {
        if (authentication != null && authentication.isAuthenticated()) {
            String username = authentication.getName();
            redisTemplate.delete("jwt:" + username);
            System.out.println("已从Redis中删除JWT: " + "jwt:" + username); // 添加日志确认
            return "登出成功！";
        }
        return "未登录";
    }

}